import { ref, onMounted, onBeforeUnmount } from "vue";

export const useKeyboard = (onShow: () => void, onHide: () => void) => {
  // const playerStore = usePlayerStore();
  const originalHeight = ref(window.innerHeight);
  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);

  // 检测 iOS 版本
  const getIOSVersion = () => {
    if (!isIOS) return null;
    const match = navigator.userAgent.match(/OS (\d+)_/);
    return match ? parseInt(match[1], 10) : null;
  };

  const iosVersion = getIOSVersion();
  const isLegacyIOS = iosVersion !== null && iosVersion <= 12;

  // 处理键盘事件
  const handleKeyboardShow = () => {
    // playerStore.setKeyboardVisible(true);
    onShow();
  };

  const handleKeyboardHide = () => {
    // playerStore.setKeyboardVisible(false);
    onHide();
  };

  // 检测键盘状态
  const checkKeyboardStatus = () => {
    const currentHeight = window.innerHeight;
    const heightDiff = originalHeight.value - currentHeight;

    // 旧版本 iOS 特殊处理
    if (isLegacyIOS) {
      // 使用更小的阈值
      if (heightDiff > 50) {
        handleKeyboardShow();
      } else {
        handleKeyboardHide();
      }
    } else {
      // 其他设备使用原有逻辑
      if (heightDiff > 100) {
        handleKeyboardShow();
      } else {
        handleKeyboardHide();
      }
    }
  };

  onMounted(() => {
    originalHeight.value = window.innerHeight;

    // 添加键盘事件监听
    window.addEventListener("resize", checkKeyboardStatus);

    // 旧版本 iOS 特殊处理
    if (isLegacyIOS) {
      // 添加输入框焦点事件监听
      document.addEventListener("focusin", () => {
        // 立即检查一次
        checkKeyboardStatus();
        // 延迟检查一次，确保捕获到键盘完全展开的状态
        setTimeout(checkKeyboardStatus, 300);
      });

      document.addEventListener("focusout", () => {
        // 立即检查一次
        checkKeyboardStatus();
        // 延迟检查一次，确保捕获到键盘完全收起的状态
        setTimeout(checkKeyboardStatus, 300);
      });
    } else {
      // 其他设备使用原有逻辑
      document.addEventListener("focusin", () => {
        setTimeout(checkKeyboardStatus, 100);
      });

      document.addEventListener("focusout", () => {
        setTimeout(checkKeyboardStatus, 100);
      });
    }
  });

  onBeforeUnmount(() => {
    // 移除事件监听
    window.removeEventListener("resize", checkKeyboardStatus);
    document.removeEventListener("focusin", checkKeyboardStatus);
    document.removeEventListener("focusout", checkKeyboardStatus);
  });

  return {
    checkKeyboardStatus
  };
};
